package com.lzx.iteam;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.*;
import com.lzx.iteam.adapter.AttendanceSubClassAdapter;
import com.lzx.iteam.base.FindViewById;
import com.lzx.iteam.base.MyBaseActivity;
import com.lzx.iteam.bean.AttendanceClassData;
import com.lzx.iteam.net.AsynHttpClient;
import com.lzx.iteam.net.GetMsgHttpReceiver;
import com.lzx.iteam.net.LocalLogin;
import com.lzx.iteam.util.AllDialogUtil;
import com.lzx.iteam.util.StringUtil;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.List;

import static android.R.attr.data;
import static com.baidu.location.b.g.o;

/**
 * Created with IntelliJ IDEA.
 * **********************************
 * User: zhangshuai
 * Date: 2016年 11月 24日
 * Time: 下午3:37
 *
 * @QQ : 1234567890
 * **********************************
 *
 * 所有班次页面（班次设置页面）
 */
public class AttendanceSubClassActivity extends MyBaseActivity implements View.OnClickListener ,AdapterView.OnItemClickListener,AdapterView.OnItemLongClickListener{

    @FindViewById(id = R.id.title_ll_back)
    private LinearLayout mLayoutBack;
    @FindViewById(id = R.id.title_tv_center)
    private TextView mTvTitle;
    @FindViewById(id = R.id.title_tv_right)
    private TextView mTvRight;
    @FindViewById(id = R.id.tv_attendance_sub_create)
    private TextView mTvSubCreate;
    @FindViewById(id = R.id.lv_attendance_sub_class)
    private ListView mListView;

    private AttendanceSubClassAdapter mAdapter;
    private ArrayList<AttendanceClassData> mDatas;
    private AttendanceClassData mSelectClassData;
    private Dialog mWaitDialog;

    private int mFlagIsNew;  // 0:考勤不存在   1: 考勤已经存在
    private String mGroupId;
    private String mFormId;

    private final int REQUEST_CODE_SUB_CREATE = 200;
    private final int DELETE_SUB = 30000;

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
            switch (msg.what){
                case DELETE_SUB:
                    httpReqDlgDismiss();
                    if (msg.arg1 == 0){
                        if (mSelectClassData != null){
                            mDatas.remove(mSelectClassData);
                            mAdapter.bindData(mDatas);
                            if (mDatas.size() == 0){
                                mTvSubCreate.setVisibility(View.VISIBLE);
                            }
                        }
                    }else {
                        Toast.makeText(mActivity, (String) msg.obj, Toast.LENGTH_LONG).show();
                    }
                    break;

            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.attendance_shifts_layout);
    }

    @Override
    public void initListener() {
        mLayoutBack.setOnClickListener(this);
        mTvRight.setOnClickListener(this);
        mTvSubCreate.setOnClickListener(this);
        mListView.setOnItemClickListener(this);
        mListView.setOnItemLongClickListener(this);
    }

    @Override
    public void initData() {

        mTvTitle.setText("班次设置");
        mTvRight.setText("保存");
        mAdapter = new AttendanceSubClassAdapter(this);
        mListView.setAdapter(mAdapter);

        Intent intent = getIntent();
        mGroupId = intent.getStringExtra("group_id");
        mFormId = intent.getStringExtra("form_id");
        if (!StringUtil.isEmpty(mFormId)){
            mFlagIsNew = 1;
            mTvRight.setVisibility(View.GONE);
        }
        mDatas = (ArrayList<AttendanceClassData>) intent.getSerializableExtra("sub_class");
        if (mDatas == null) {
            mDatas = new ArrayList<>();
        }
        if (mDatas.size() > 0){
            mTvSubCreate.setVisibility(View.GONE);
            mAdapter.bindData(mDatas);
        }else{
            mTvSubCreate.setVisibility(View.VISIBLE);
        }

    }

    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.title_ll_back:
                if (mFlagIsNew == 1){
                    backActivity();
                }else{
                    finish();
                }
                break;
            case R.id.title_tv_right:
                backActivity();
                break;
            case R.id.tv_attendance_sub_create:
                createNewShift();
                break;

        }
    }

    /**
     * 返回设置页面
     */
    private void backActivity(){
        if (mDatas.size() >= 0){
            Intent sub = new Intent();
            sub.putExtra("sub_class",mDatas);
            setResult(RESULT_OK,sub);
        }
        finish();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(this,AttendanceSubClassEditActivity.class);
        AttendanceClassData data = mDatas.get(position);
        data.setPositon(position);
        intent.putExtra("position",position);
        intent.putExtra("sub_class",data);
        intent.putExtra("sub_classes",mDatas);
        intent.putExtra("group_id",mGroupId);
        intent.putExtra("form_id",mFormId);
        startActivityForResult(intent,REQUEST_CODE_SUB_CREATE);

    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        mSelectClassData = mDatas.get(position);
        showCancelSetDlg();
        return true;
    }

    /**
     * 删除班次提醒
     */
    public void showCancelSetDlg() {
        String okText = this.getString(R.string.label_btn_ok);
        String cancelText = this.getString(R.string.cancel);
        String notice = "是否确定删除\n班次" + mSelectClassData.getSub_name();
        mDialogUtil.titleDeleteMsgStyle(okText, cancelText, notice);
        mDialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {
            @Override
            public void onConfirmClick(Dialog lDialog) {
                lDialog.dismiss();
                if (mFlagIsNew == 0){
                    mDatas.remove(mSelectClassData);
                    mAdapter.bindData(mDatas);
                }else{
                    httpReqDlgShow();
                    deleteSub(mSelectClassData);
                }
            }

            @Override
            public void onCancelClick(Dialog lDialog) {
                lDialog.dismiss();
            }
        });
    }



    /**
     * 创建新的班次
     */
    public void createNewShift(){
        if (mDatas.size() >= 20){
            Toast.makeText(AttendanceSubClassActivity.this, "最多可设置二十个班次", Toast.LENGTH_SHORT).show();
        }else{
            Intent intent = new Intent(this,AttendanceSubClassEditActivity.class);
            intent.putExtra("position",-1);
            intent.putExtra("group_id",mGroupId);
            intent.putExtra("form_id",mFormId);
            intent.putExtra("sub_classes",mDatas);
            startActivityForResult(intent,REQUEST_CODE_SUB_CREATE);
        }

    }

    /**
     * 删除班次
     * @param data
     */
    private void deleteSub(AttendanceClassData data){
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
              .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, mGroupId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_FORM_ID, mFormId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SUB_ID, data.get_id()));

        GetMsgHttpReceiver msg = new GetMsgHttpReceiver(mHandler.obtainMessage(DELETE_SUB));
        msg.mApi = AsynHttpClient.API_EVENT_ATTENDANCE_DEL_CLOCK;
        msg.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(msg);
    }

    /**
     * 显示等待的dialog
     */
    private void httpReqDlgShow() {
        if (mWaitDialog == null) {
            mWaitDialog = mDialogUtil.waitDialog();
//            mProgressDialog.setCancelable(false);
            if (!mWaitDialog.isShowing()){
                mWaitDialog.show();
            }
        }

    }

    /**
     * 取消等待的dialog
     */
    private void httpReqDlgDismiss() {
        if (mWaitDialog != null && mWaitDialog.isShowing()) {
            mWaitDialog.dismiss();
            mWaitDialog = null;
        }
    }

    @Override
    public void onBackPressed() {
        if (mFlagIsNew == 1){
            backActivity();
        }
        super.onBackPressed();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == RESULT_OK){
            switch (requestCode){
                case REQUEST_CODE_SUB_CREATE:
                    AttendanceClassData backData = (AttendanceClassData) data.getSerializableExtra("sub_class");
                    int position = backData.getPositon();
                    if (position == -1){
                        int count = mDatas.size();
                        if (count == 0){
                            backData.setPositon(0);
                        }else{
                            backData.setPositon(count);
                        }
                        mDatas.add(backData);
                    }else{
                        mDatas.set(position,backData);
                    }
                    if (mDatas.size() > 0){
                        mTvSubCreate.setVisibility(View.GONE);
                    }else{
                        mTvSubCreate.setVisibility(View.VISIBLE);
                    }
                    mAdapter.bindData(mDatas);
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


}
